package com.jprocms.module.cms.controller.portal.page;

import com.jprocms.module.cms.dal.dataobject.content.TagDO;
import com.jprocms.module.cms.dal.dataobject.site.SiteDO;
import com.jprocms.module.cms.enums.ErrorCodePortalConstants;
import com.jprocms.module.cms.exception.PortalServiceExceptionUtil;
import com.jprocms.module.cms.service.content.ContentCountService;
import com.jprocms.module.cms.service.content.TagService;
import com.jprocms.module.cms.service.site.SiteService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Tag Controller
 *
 * @author jprocms
 */
@Controller("frontendTagController")
public class TagController {

    private static final String TAG_LIST = "sys/tag_list";

    private static final String TAG_DETAIL = "sys/tag_detail";


    private final SiteService siteService;
    private final TagService service;
    private final ContentCountService contentCountService;

    public TagController(SiteService siteService, TagService service, ContentCountService contentCountService) {
        this.siteService = siteService;
        this.service = service;
        this.contentCountService = contentCountService;
    }

    @GetMapping({"/tag", "/{sitePath:[\\w-]+}/tag"})
    public String index(@PathVariable(required = false) String sitePath, HttpServletRequest request) {
        SiteDO site = siteService.getSite(sitePath);
        contentCountService.viewIndex(site.getId());
        return site.joinTemplate(TAG_LIST);
    }

    @GetMapping({"/tag/{id}", "/{sitePath:[\\w-]+}/tag/{id}"})
    public String tagDetail(@PathVariable(required = false) String sitePath, @PathVariable Long id,
                            HttpServletRequest request, Map<String, Object> modelMap) {
        SiteDO site = siteService.getSite(sitePath);
        TagDO tag = service.getTag(id);
        if (tag == null) {
            throw PortalServiceExceptionUtil.exception(ErrorCodePortalConstants.DATA_NOT_EXIST);
        }
        modelMap.put("tag", tag);
        contentCountService.viewIndex(site.getId());
        return site.joinTemplate(TAG_DETAIL);
    }

}
